import axios from 'axios'
import { useRef, useState } from 'react'

export default function Home() {
  const fileRef = useRef<HTMLInputElement>(null)
  const imgRef = useRef<HTMLImageElement>(null)
  const fileCaptureRef = useRef<HTMLInputElement>(null)
  const [loading, setLoading] = useState(false)

  function handleSubmit(e: React.ChangeEvent<HTMLInputElement>) {
    if (!e.target.files?.length) return alert('请选择文件')

    const formData = new FormData()
    formData.append('file', e.target.files[0])
    setLoading(true)
    axios.post('/api/oss/upload', formData).then((res) => {
      setLoading(false)
      if (imgRef.current) imgRef.current.src = res.data.data
      alert('上传成功')
    })
  }

  // 拍照上传
  function handleCapture(e: React.MouseEvent<HTMLButtonElement>) {
    e.preventDefault()
    e.stopPropagation()
    fileCaptureRef.current?.click()
  }

  // 相册上传
  function handleAlbum(e: React.MouseEvent<HTMLButtonElement>) {
    e.preventDefault()
    e.stopPropagation()
    fileRef.current?.click()
  }

  return (
    <div>
      <button type="button" onClick={handleAlbum}>
        相册
      </button>
      <button type="button" onClick={handleCapture}>
        拍照
      </button>
      {loading && <div>上传中...</div>}
      <input
        type="file"
        name="file"
        ref={fileRef}
        accept="image/*"
        hidden
        onChange={handleSubmit}
      />
      <input
        type="file"
        name="file"
        ref={fileCaptureRef}
        accept="image/*"
        capture="user"
        hidden
        onChange={handleSubmit}
      />
      <br />
      <img ref={imgRef} />
    </div>
  )
}
